package me.sealer.utils;

import me.sealer.model.Location;
import me.sealer.model.baiduweather.BaiduWeatherResult;
import me.sealer.model.baiduweather.Index;
import me.sealer.model.baiduweather.Result;
import me.sealer.model.baiduweather.WeatherData;
import net.sf.json.JSONObject;

/**
 * Created by sealer on 10-31-2017.
 */
public class WeatherUtil {

    public static final String BAIDU_WEATHER_URL = "http://api.map.baidu.com/telematics/v3/weather?location=CITY&output=json&ak=MYKEY";
    public static final String MY_BAIDU_WEATHER_KEY = "DrNbLx4ZFRg8KbLoXhkCZeL9";

    /**
     * 先用ip获取位置
     * 再用位置获取天气
     * 调用该方法获得天气
     *
     * @param ip
     * @return
     */
    public static String retrieveWeatherByIp(String ip) {
        Location location = LocationUtil.retrieveLocationByIp(ip);
        String city = location.getCity();
        String strWeather = retrieveWeatherByLocation(city);
        return strWeather;
    }

    public static String retrieveWeatherByLocation(String location) {
        String url = null;
        StringBuffer sb = new StringBuffer();
        sb.append(location + ":\n");
        url = BAIDU_WEATHER_URL.replace("MYKEY", MY_BAIDU_WEATHER_KEY).replace("CITY", location);
//		System.out.println(url);
        JSONObject jsonObject = HttpUtil.doGetStr(url);
        String status = jsonObject.getString("status");
//		System.out.println(status);
//		System.out.println(jsonObject);
        if ("success".equals(status)) {
            BaiduWeatherResult baiduWeatherResult = (BaiduWeatherResult) JSONObject.toBean(jsonObject, BaiduWeatherResult.class);
            Result result = baiduWeatherResult.getResults()[0];
            WeatherData weatherData = result.getWeather_data()[0];//只获取当天数据  0代表当天
            sb.append(weatherData.getDate() + "\n");
            sb.append("温度: " + weatherData.getTemperature() + "\n");
            sb.append("天气: " + weatherData.getWeather() + "\n");
            sb.append("风力: " + weatherData.getWind() + "\n");
            String pm25 = result.getPm25();
            sb.append("PM2.5: " + pm25 + "\n");
            Index[] index = result.getIndex();
            for (Index i : index) {
                sb.append(i.getTipt() + ": " + i.getZs() + "\n");
            }

        }

        return sb.toString();
    }

}